package com.gold.security;

import com.gold.common.CacheUtils;
import com.gold.common.DateUtils;
import com.gold.dao.RoleDao;
import com.gold.entity.User;
import com.gold.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**自定义登录认证方式
 * @author XiaoHao
 * @date 2022-05-09 16:35
 */
@Component
@Slf4j
public class LoginValidateAuth implements AuthenticationProvider {

    @Autowired
    UserService userService;
    @Autowired
    RoleDao roleDao;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //获取输入的用户名
        String username = authentication.getName();
        //获取输入的明文密码
        String credentials = (String)authentication.getCredentials();
        //查询用户是否存在
        User user = new User();
        user.setUsername(username);
        user = userService.getUserCardId(user);

        if (user==null){
            throw new UsernameNotFoundException("用户或密码错误");
        }
        if ("1".equals(user.getState())){
            throw new UsernameNotFoundException("账号已锁定，请联系管理员");
        }
        if ("2".equals(user.getState())){
            throw new UsernameNotFoundException("账号已过期，请联系管理员");
        }
        if (user.getCardInfo()==null||!DateUtils.compare(user.getCardInfo().getEndTime(),new Date())){
            throw new UsernameNotFoundException("卡密已过期，请联系管理员");
        }
        if (!user.getPassword().equals(credentials)){
            loginNum(username,user);
            throw new BadCredentialsException("用户或密码错误");
        }
        //查询用户角色
        Set<String> roleName = roleDao.selecRolesByUserName(username);
        if (roleName!=null && roleName.size()>0){
            //封装角色信息
            List<GrantedAuthority> list = roleName.stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role)).collect(Collectors.toList());
            user.setAuthorities(list);
        }
        log.info("用户{}登录成功",username);
        return new UsernamePasswordAuthenticationToken(user,credentials,user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.equals(UsernamePasswordAuthenticationToken.class);
    }

    /**
     * 限制登录次数
     * @param name
     */
    public void loginNum(String name,User user){
        String s = CacheUtils.get(name);
        if (s!=null&&s!=""){
            Integer integer = Integer.valueOf(s);
            if (integer>=5){
                //清除缓存中当前用户的数据
                CacheUtils.del(name);
                user.setState("1");
                userService.update(user);
                throw new UsernameNotFoundException("账号输入错误超过五次，账号已锁定，请联系管理员");
            }else {
                integer++;
                CacheUtils.set(name,integer.toString());
            }
        }else {
            CacheUtils.set(name,"1");
        }
    }
}
